package easy;

public class Solution_492 {
    public int[] constructRectangle(int area) {
        int middle = (int)sqrt(area, 0);
        for (int i = middle;; i--) {
            if (area%i != 0) {
                continue;
            }
            return new int[]{area / i, i};
        }
    }

    /*public int[] constructRectangle(int area) {
        if (area == 1) {
            return new int[]{1, 1};
        }
        int middle = area / 2, W = 1, L = area;
        for (int i = middle;; i--) {
            if (area%i != 0) {
                continue;
            }
            int j = area / i;
            if (i < j) {
                break;
            }
            if ((L-W) > (i - j)) {
                L = i;
                W = j;
            }
        }
        return new int[]{L, W};
    }*/

    public int sqrt(int area) {
        int x = area / 2;
        while (true) {
            x = (x + area/x)/2;
            if (x*x == area) {
                return x;
            }
        }
    }

    public float sqrt(float area, double scare) {
        float x = area, last;
        while (true) {
            last = x;
            x = (x + area/x)/2;
            if (Math.abs(last - x) <= scare) {
                return x;
            }
        }
    }

    float SqrtByNewton(float x, double eps) {
        float val = x;//最终
        float last;//保存上一个计算的值
        do {
            last = val;
            val = (val + x / val) / 2;
        } while (Math.abs(val - last) > eps);
        return val;
    }

        public static void main(String[] args) {
        Solution_492 model = new Solution_492();
//        System.out.println(model.constructRectangle(4)[0] + "," + model.constructRectangle(4)[1]);
        System.out.println(model.constructRectangle(1)[0] + "," + model.constructRectangle(1)[1]);
        System.out.println(model.constructRectangle(99)[0] + "," + model.constructRectangle(99)[1]);
//        System.out.println(model.sqrt(256.0f, 0.001));
//        System.out.println(model.sqrt(256.0f, 0.00001));
//        System.out.println(model.sqrt(256.0f, 0));
//        System.out.println(model.sqrt(15241.5568f, 0));
//        System.out.println(model.SqrtByNewton(15241.5568f, 0));
    }
}
